package com.qyb.barcode;

import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.qyb.util.BufferedImageLuminanceSource;
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 实现功能：
 * <p/>
 *
 * @author 秦有宝
 * @version 1.0.00
 */
public class BarcodePdfUtils {

    @Test
    public void ParsePdf () throws IOException {
        File file = new File("D:/tt/7.pdf");
        InputStream input = new FileInputStream(file);
        PdfReader reader = new PdfReader(input);
//        PdfReader reader = new PdfReader("D:/test/scanner.pdf");

        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        ImageRenderListener2 listener = new ImageRenderListener2();
        int pageNum = reader.getNumberOfPages();
        for (int i = 1; i <= pageNum; i++) {
            parser.processContent(i, listener);
        }
        reader.close();
        List<byte[]> imageBytes = listener.getImageAsBytes();

        for (int i = 0; i <imageBytes.size() ; i++) {
            BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageBytes.get(i)));
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap bitmap = new BinaryBitmap(binarizer);
            HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
            decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

            Result result = null;
            try {
                result = new MultiFormatReader().decode(bitmap, decodeHints);
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
            if(result != null){
                String decode = result.getText();
                System.out.println(decode); //输出到控制台
            }

        }


    }

}
